import React, { useEffect, useState } from 'react';
import { Select } from 'antd';
// @ts-ignore
import { CaretDownOutlined } from '#/utils/antdIcons';
import type { IOptionType } from '../../type';

interface IProps {
  /**
   * 选择事件
   */
  onChange?: (values: string[]) => void;
  /**
   * 点击事件
   */
  onClick?: any;
  /**
   * 选择值
   */
  value?: string[];
  /**
   * 选项
   */
  options?: IOptionType[];
  /**
   * 占位符
   */
  placeholder?: string;
  /**
   * 最多显示几个标签
   */
  maxTagCount?: number;
  /**
   * 显示几个字
   */
  maxTagTextLength?: number;
  /**
   * 是否显示下拉小箭头
   */
  showArrow?: boolean;

  /**
   * 是否展开
   */
  open?: boolean;
  /**
   * logo
   */
  logo?: React.ReactNode;
  /**
   * 全选时显示名称
   */
  alltitle?: string;

  /**
   * 样式
   */
  style?: any;
}

const SelectAll = (props: IProps) => {
  const {
    onChange,
    onClick,
    value,
    options = [],
    logo = <CaretDownOutlined />,
    showArrow,
    open,
    maxTagCount,
    maxTagTextLength,
    alltitle = '全部',
    placeholder,
    ...rest
  } = props;
  const [checkedList, setCheckedList] = useState<any[]>();

  useEffect(() => {
    if (value) {
      setCheckedList(value);
    }
  }, [value]);

  const _onClick = async () => {
    if (onClick) {
      const data = await onClick();
      setCheckedList(data);
      onChange && onChange(data);
    }
  };

  const _onChange = (e: any) => {
    if (typeof e === 'string') {
      setCheckedList([e]);
      onChange && onChange([e]);
    } else {
      setCheckedList(e);
      onChange && onChange(e);
    }
  };

  return (
    <Select
      {...rest}
      // mode={checkedList?.length === options?.length ? undefined : 'multiple'}
      suffixIcon={logo}
      // value={checkedList?.length === options?.length ? alltitle : checkedList}
      value={
        !checkedList?.length
          ? placeholder
          : checkedList?.length === options?.length
          ? alltitle
          : `${checkedList?.length}项/${options?.length}项`
      }
      options={options as any}
      showArrow={showArrow}
      open={open}
      onChange={_onChange}
      maxTagTextLength={maxTagTextLength}
      maxTagCount={maxTagCount}
      onClick={_onClick}
    />
  );
};

export default SelectAll;
